using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Microsoft.Office.Project.EPMSync.Config.Library;
using System.Data.SqlClient;
using System.Net;
using PSLibrary = Microsoft.Office.Project.Server.Library;
using System.Threading;
using System.Reflection;
using System.Collections.ObjectModel;
using Microsoft.Office.Project.EPMSync.Config.Editor.Properties;
using System.Globalization;

namespace Microsoft.Office.Project.EPMSync.Config.Editor
{
    public partial class FormMain : Form
    {
        private SyncConfigFile _configFile;
        private SyncConfig _config;
        private bool _loading;
        private Color _BackgroundColor;
        private Color _CheckboxBackgroundColor;
        private DateTime timeoutTime;

        public FormMain()
        {
            OpenSplash(3);

            InitializeComponent();
        }

        #region Initialize Form Data
        private void frmMain_Load(object sender, EventArgs e)
        {
            _loading = true;
            // Read configuration file
            Assembly epmAssembly = Assembly.GetExecutingAssembly();
            string fullPath = epmAssembly.Location;
            string directory = fullPath.Substring(0, fullPath.LastIndexOf(@"\") + 1);

            _configFile = new SyncConfigFile(directory + "EPMSync.config");
            //_configFile = new SyncConfigFile();
            _config = _configFile.SyncConfiguration;
            _BackgroundColor = textBoxDBConn.BackColor;
            _CheckboxBackgroundColor = checkBoxPublish.BackColor;

            if (_config != null)
            {
                LoadConfigToForm();
            }
            else
            {
                RightAwareMessageBox.Show(Resources.LoadFailed, Resources.EditorTitle, MessageBoxButtons.OK, MessageBoxIcon.Error);
                FormSplash.CloseForm();
                this.Close();
            }

            CloseSplash();

            _loading = false;
        }

        private void OpenSplash(int time)
        {
            timeoutTime = DateTime.Now.AddSeconds(time);

            FormSplash.ShowSplashScreen();
            Application.DoEvents();

        }

        private void CloseSplash()
        {
            do
            {
                if (DateTime.Now > timeoutTime)
                {
                    FormSplash.CloseForm();
                    return;
                }
                Application.DoEvents();
                Thread.Sleep(500);
            }
            while (true);

        }

        private void LoadConfigToForm()
        {
            textBoxDBConn.Text = _config.PortfolioServerDatabaseConnectionString;
            textBoxPSURL.Text = _config.ProjectServerURL;
            textBoxWakeup.Text = _config.WakeupInterval.ToString(CultureInfo.InvariantCulture);
            textBoxAccountID.Text = _config.AccountID.ToString(CultureInfo.InvariantCulture);
            checkBoxPublish.Checked = _config.PublishAfterSave;
            UpdateCountExcludedProjects();
            UpdateCountFieldMappings();

        }

        private void UpdateCountExcludedProjects()
        {
            labelCountExcludedProjects.Text = String.Format(CultureInfo.InvariantCulture, Resources.ExcludedProjectsLabel, _config.ExcludedProjects.Count.ToString(CultureInfo.InvariantCulture));
        }

        private void UpdateCountFieldMappings()
        {
            labelCountFieldsMapped.Text = String.Format(CultureInfo.InvariantCulture, Resources.FieldsMappedLabel, _config.FieldMappings.Count.ToString(CultureInfo.InvariantCulture));
        }

        #endregion

        #region Methods for calling externally from the forms

        public void UpdateExcludedProjects(Collection<Guid> excludedProjects)
        {
            _config.ExcludedProjects = excludedProjects;
            UpdateCountExcludedProjects();
            labelCountExcludedProjects.BackColor = Color.Yellow;
            buttonSave.Enabled = true;
            buttonCancel.Text = Resources.ButtonCancel;

        }

        public void UpdateFieldMappings(Collection<FieldMapping> fieldMappings)
        {
            _config.FieldMappings = fieldMappings;
            UpdateCountFieldMappings();
            labelCountFieldsMapped.BackColor = Color.Yellow;
            buttonSave.Enabled = true;
            buttonCancel.Text = Resources.ButtonCancel;
        }

        public void UpdateSqlConnectionString(string sqlConnectionString)
        {
            textBoxDBConn.Text = sqlConnectionString;
        }

        #endregion

        #region Data Changed Events

        private void ResetColor()
        {
            textBoxDBConn.BackColor = _BackgroundColor;
            textBoxPSURL.BackColor = _BackgroundColor;
            textBoxWakeup.BackColor = _BackgroundColor;
            textBoxAccountID.BackColor = _BackgroundColor;
            checkBoxPublish.BackColor = _CheckboxBackgroundColor;
            labelCountFieldsMapped.BackColor = _CheckboxBackgroundColor;
            labelCountExcludedProjects.BackColor = _CheckboxBackgroundColor;

        }

        private void textBoxDBConn_TextChanged(object sender, EventArgs e)
        {
            if (!_loading)
            {
                textBoxDBConn.BackColor = Color.Yellow;
                buttonSave.Enabled = true;
                buttonCancel.Text = Resources.ButtonCancel;
            }
        }

        private void textBoxPSURL_TextChanged(object sender, EventArgs e)
        {
            if (!_loading)
            {
                textBoxPSURL.BackColor = Color.Yellow;
                buttonSave.Enabled = true;
                buttonCancel.Text = Resources.ButtonCancel;
            }
        }

        private void textBoxWakeup_TextChanged(object sender, EventArgs e)
        {
            if (!_loading)
            {
                textBoxWakeup.BackColor = Color.Yellow;
                buttonSave.Enabled = true;
                buttonCancel.Text = Resources.ButtonCancel;
            }
        }

        private void textBoxAccountID_TextChanged(object sender, EventArgs e)
        {
            if (!_loading)
            {
                textBoxAccountID.BackColor = Color.Yellow;
                buttonSave.Enabled = true;
                buttonCancel.Text = Resources.ButtonCancel;
            }
        }

        private void checkBoxPublish_CheckStateChanged(object sender, EventArgs e)
        {
            if (!_loading)
            {
                checkBoxPublish.BackColor = Color.Yellow;
                buttonSave.Enabled = true;
                buttonCancel.Text = Resources.ButtonCancel;
            }
        }

        #endregion

        #region Button Events

        private void buttonCancel_Click(object sender, EventArgs e)
        {
            if (buttonCancel.Text == Resources.ButtonCancel)
            {
                DialogResult dr = RightAwareMessageBox.Show(String.Format(CultureInfo.InvariantCulture, Resources.DiscardChanges, Resources.ButtonOK, Resources.ButtonClose), Resources.EditorTitle, MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
                if (dr == DialogResult.OK)
                {
                    FormMain.ActiveForm.Close();
                }
            }
            else
                FormMain.ActiveForm.Close();

        }

        private void buttonSave_Click(object sender, EventArgs e)
        {
            Cursor.Current = System.Windows.Forms.Cursors.WaitCursor;

            _config.PortfolioServerDatabaseConnectionString = textBoxDBConn.Text;
            _config.ProjectServerURL = textBoxPSURL.Text;
            _config.WakeupInterval = Convert.ToInt32(textBoxWakeup.Text, CultureInfo.InvariantCulture);
            _config.AccountID = Convert.ToInt32(textBoxAccountID.Text, CultureInfo.InvariantCulture);
            _config.PublishAfterSave = checkBoxPublish.Checked;

            if (_configFile.WriteConfigToFile())
            {
                ResetColor();
                buttonSave.Enabled = false;
                buttonCancel.Text = Resources.ButtonClose;
            }
            else
            {
                RightAwareMessageBox.Show(Resources.SaveFailed, Resources.EditorTitle, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            Cursor.Current = System.Windows.Forms.Cursors.Default;

        }

        private void buttonEditProject_Click(object sender, EventArgs e)
        {
            if (textBoxPSURL.Text.Length > 0)
            {
                Cursor.Current = System.Windows.Forms.Cursors.WaitCursor;
                FormEditExcludedProjects eep = new FormEditExcludedProjects(this);
                if (eep.SetLists(textBoxPSURL.Text, _config.ExcludedProjects))
                {
                    Cursor.Current = System.Windows.Forms.Cursors.Default;
                    eep.ShowDialog(this);
                }
                Cursor.Current = System.Windows.Forms.Cursors.Default;
            }
            else
            {
                RightAwareMessageBox.Show(Resources.MissingPSURL, Resources.EditorTitle, MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        private void buttonEditMapping_Click(object sender, EventArgs e)
        {
            if ((textBoxPSURL.Text.Length > 0) && (textBoxDBConn.Text.Length > 0) && (textBoxAccountID.Text.Length > 0))
            {
                Cursor.Current = System.Windows.Forms.Cursors.WaitCursor;
                FormEditFieldMappings efm = new FormEditFieldMappings(this);
                if (efm.SetLists(textBoxPSURL.Text, textBoxDBConn.Text, textBoxAccountID.Text, _config.FieldMappings))
                {
                    Cursor.Current = System.Windows.Forms.Cursors.Default;
                    efm.ShowDialog(this);
                }
                Cursor.Current = System.Windows.Forms.Cursors.Default;
            }
            else
            {
                RightAwareMessageBox.Show(Resources.MissingInitialInfo, Resources.EditorTitle, MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        private void buttonAbout_Click(object sender, EventArgs e)
        {
            FormAbout ab = new FormAbout();
            ab.Show(this);
        }

        private void buttonConnectionWizard_Click(object sender, EventArgs e)
        {
            FormBuildConnectionString bcs = new FormBuildConnectionString(this, this.textBoxDBConn.Text);
            bcs.ShowDialog();
        }

       #endregion



    }
}